<?php

extract(extractPost(), EXTR_PREFIX_ALL, 'p');
/*  šifra projekta  naziv projekta,  ime naročnika    datum začetka,   datum zaključka,   razvojna skupina */
 if(isset($p_code) && isset($p_name) && isset($p_client) && isset($p_start) && isset($p_finish) && isset($p_groupId)){
     
    /* If project id parameter is not set we create new project */
    if(!isset($p_id)){ 
     
     
        $project_exists = R::findOne('project',' code = ? ', array( $p_code ));
        $result = array();

        if($project_exists){
            jsonErrorDie("Project code already exists. Please use another one.");

        }
        
        /* Create new project. */
        $p = R::dispense( 'project' );
        $p->start = $p_start;
        $p->active = 1;
        
    } else {
        /* Load existing project */
    
        $p = R::load('project', $p_id);
        if($p->id == 0){
            jsonErrorDie("This project does not exist.");
        }
    }
    
    $today = date("Y-m-d");
    $today = strtotime($today);
    $startCompare = strtotime($p_start);
    $finishCompare = strtotime($p_finish);
   
    
    if($today >= $startCompare){
        if($startCompare < $finishCompare){
            
            $p->code = $p_code;
            $p->name = $p_name;
            $p->client = $p_client;
            
//            $group = R::load('group', $p_groupId);
//            $p->productOwner = $group->product_owner;
            
            $p->finish = $p_finish;
            $p->dev_group = $p_groupId;
	        $p->created_date = R::isoDateTime();
            
            $p_id = R::store( $p );
            
         
            
            
        } else {
            /* Start date must be before finish date */
            jsonErrorDie("Start date must be before finish date.");
        }
        
    } else {
        /* Please pick a date in the future */
        jsonErrorDie("Please pick a date up to now.");
    }
    
    
    if(isset($p_id)){
//        $result["project_id"] = $p_id;
        jsonSuccessDie("project_id", $p_id);
    }
 } else {
     jsonErrorDie("Problem occured while inserting project in database.");
 }
 
echo json_encode($result);
        

 
?>

